package org.flyking.tool;

import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.flyking.data.Requirement;

import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.List;

public class Write {
    public static void exportToWord(List<Requirement> requirements, String outputPath) {
        try (XWPFDocument document = new XWPFDocument()) {
            int i=0;
            for (Requirement req : requirements) {
                // 创建标题（属性名）
                XWPFParagraph titlePara = document.createParagraph();
                titlePara.setStyle("Heading1");
                XWPFRun titleRun = titlePara.createRun();
                titleRun.setText("需求"+i);
                titleRun.setBold(true);
                titleRun.setFontSize(20);
                titleRun.addBreak();

                addRequirementToDocument(document, req,++i);
            }

            // 保存Word文档
            try (FileOutputStream out = new FileOutputStream(outputPath)) {
                document.write(out);
            }
            System.out.println("Word文档生成成功: " + outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void addRequirementToDocument(XWPFDocument document, Requirement req,int paraGraph) {
        // 使用反射获取所有属性
        Field[] fields = Requirement.class.getDeclaredFields();
        int i=0;

        for (Field field : fields) {
            i++;
            field.setAccessible(true); // 允许访问私有字段

            try {
                String fieldName = i+"、"+field.getName();
                Object value = field.get(req);

                // 创建标题（属性名）
                XWPFParagraph titlePara = document.createParagraph();
                titlePara.setStyle("Heading2");
                XWPFRun titleRun = titlePara.createRun();
                titleRun.setText(fieldName);
                titleRun.setBold(true);
                titleRun.setFontSize(14);
                titleRun.addBreak();

                // 创建内容（属性值）
                XWPFParagraph contentPara = document.createParagraph();
                XWPFRun contentRun = contentPara.createRun();
                contentRun.setText(value != null ? value.toString() : "N/A");
                contentRun.setFontSize(12);
                contentRun.addBreak();//contentRun.addBreak(BreakType.TEXT_WRAPPING);
            } catch (IllegalAccessException e) {
                System.err.println("无法访问字段: " + field.getName());
            }
        }

        // 添加分隔线
        XWPFParagraph separator = document.createParagraph();
        XWPFRun separatorRun = separator.createRun();
        separatorRun.setText("-----------------------------");
        separatorRun.addBreak(BreakType.PAGE);
    }

}
